package com.vf.s.common.plugins.shiro;


import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Component;

import com.jfinal.kit.JsonKit;
import com.jfinal.log.Log;
import com.vf.core.render.RenderBean;



//添加注释，该注释很重要，需要 覆盖掉authc 方法的过滤器 
@Component("LoginFormFilter")
public class LoginFormFilter extends FormAuthenticationFilter {
	protected final Log log = Log.getLog(getClass());

	/**
	 * 在访问controller前判断是否登录，返回json，不进行重定向。
	 * 
	 * @param request
	 * @param response
	 * @return true-继续往下执行，false-该filter过滤器已经处理，不继续执行其他过滤器
	 * @throws Exception
	 */
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		
		try {
			
			HttpServletResponse httpServletResponse = (HttpServletResponse) response;
			HttpServletRequest req = (HttpServletRequest) request;
	        if (isLoginRequest(request, response)) {
	            if (isLoginSubmission(request, response)) {
	                return executeLogin(request, response);
	            } else {
	                return true;
	            }
	        } else {
	        	if(isAjaxRequest(req)) {
	    			StringBuilder sb = new StringBuilder();
	        		String port = "";
	        		if (request.getServerPort() != 80) {
	        			port = ":" + request.getServerPort();

	        			sb.append(request.getScheme()).append("://").append(request.getServerName()).append(port)
	        					.append(req.getContextPath()).append("/login");

	        		}else {
	        			sb.append(request.getScheme()).append("://").append(request.getServerName())
	        					.append(req.getContextPath()).append("/login");
	        		}
	        		
	        		RenderBean renderBean=new RenderBean();
					renderBean.setCode(403);
					renderBean.setMessage("请先登录!");
					renderBean.setData(sb.toString());
					httpServletResponse.setCharacterEncoding("UTF-8");
					httpServletResponse.setContentType("application/json");
					httpServletResponse.setStatus(403);
					httpServletResponse.setHeader("REDIRECT", "REDIRECT");// 告诉ajax这是重定向
					httpServletResponse.setHeader("CONTEXTPATH", sb.toString());// 重定向地址
					httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
					httpServletResponse.getWriter().write(JsonKit.toJson(renderBean));
	        	}
	        	else {
	    			this.setLoginUrl(ShiroKit.getLoginUrl());
	                saveRequestAndRedirectToLogin(request, response);
	        	}
	    		return false;
	        }
		}catch (Exception e) {
		}
		return false;
	}
	
	public static boolean isAjaxRequest(HttpServletRequest request) {
		String requestedWith = request.getHeader("x-requested-with");
		if (requestedWith != null && requestedWith.equalsIgnoreCase("XMLHttpRequest")) {
			return true;
		} else {
			return false;
		}
	}

}